﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Newtonsoft.Json;
using RazorEngine;

namespace PublishSoftwareWebPageCreator
{
    public partial class MainForm : Form
    {


        List<Page> pages;
        string pagesJsonFile = "pages.json";

        UTF8Encoding utf8 = new UTF8Encoding(false);

        public MainForm()
        {
            InitializeComponent();

            if (File.Exists(pagesJsonFile))
            {
                string json = File.ReadAllText(pagesJsonFile, utf8);
                this.pages = JsonConvert.DeserializeObject<List<Page>>(json);
            }
            else
            {
                this.pages = new List<Page>();
            }

            foreach(var p in this.pages)
            {
                cb_pages.Items.Add(p);
            }

            if (cb_pages.Items.Count > 0)
            {
                cb_pages.SelectedIndex = 0;
            }
        }


        private void bt_create_Click(object sender, EventArgs e)
        {
            NewPageForm newPageForm = new NewPageForm();
            if(newPageForm.ShowDialog() == DialogResult.OK)
            {
                this.pages.Add(newPageForm.page);
                var json = JsonConvert.SerializeObject(this.pages);
                File.WriteAllText(pagesJsonFile, json, utf8);

                cb_pages.Items.Insert(0, newPageForm.page);
                cb_pages.SelectedIndex = 0;

                lb_msg.Text = "成功新建";
            }
        }

        private void bt_cut_Click(object sender, EventArgs e)
        {
            if (cb_pages.SelectedItem != null)
            {
                CutImageForm cf = new CutImageForm((Page)cb_pages.SelectedItem);
                if(cf.ShowDialog() == DialogResult.OK)
                {
                    string picPath = "asset/" + cf.picFileName;
                    Clipboard.SetDataObject(picPath, false);
                    lb_msg.Text = "图片路径已经复制到剪贴板";
                }
            }
        }

        private void bt_save_ClickAsync(object sender, EventArgs e)
        {
            save();
        }

        private async void save()
        {
            if (cb_pages.SelectedItem != null)
            {
                var p = (Page)cb_pages.SelectedItem;
                string datapath = p.takeDir() + "\\data.json";
                string dataobjpath = p.takeDir() + "\\dataobj.json";
                string json = await editorBrowser.ExecuteScriptAsync("getJson()");
                json = Regex.Unescape(json).Trim('"');
                PageJson pageJson = JsonConvert.DeserializeObject<PageJson>(json);

                File.WriteAllText(datapath, json, utf8);
                File.WriteAllText(dataobjpath, "var dataobj=" + json, utf8);
                File.Delete(p.takeDir() + "\\index.html");

                create_index_html(p, pageJson);
                editorBrowser.Reload();
                previewBrowser.Reload();
            }
        }

        public void create_index_html(Page page, PageJson data)
        {
            string template = File.ReadAllText("template.cshtml");
            var html = Razor.Parse(template, data);
            File.WriteAllText(page.takeDir() + "\\index.html", html, utf8);
        }

        private void cb_pages_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_pages.SelectedItem != null)
            {
                var p = (Page)cb_pages.SelectedItem;
                FileInfo indexhtml = new FileInfo(p.takeDir() + "\\index.html");
                FileInfo editorhtml = new FileInfo(p.takeDir() + "\\editor.html");
                editorBrowser.Source = new Uri(editorhtml.FullName);
                previewBrowser.Source = new Uri(indexhtml.FullName);
            }
        }

        private void bt_pub_php_Click(object sender, EventArgs e)
        {
            if (cb_pages.SelectedItem != null)
            {
                var p = (Page)cb_pages.SelectedItem;
                var srcdir = p.takeDir();
                var dir = p.takeDir() + "\\php";
                if (Directory.Exists(dir)) Directory.Delete(dir, true);
                Directory.CreateDirectory(dir);
                Directory.CreateDirectory(dir + "\\asset");

                List<String> cpFiles = new List<string>();
                cpFiles.Add("index.php");
                cpFiles.Add("data.json");
                cpFiles.Add("index.html");

                string json = File.ReadAllText(srcdir + "\\data.json");
                Regex r = new Regex("asset/.*?\"");
                var ms = r.Matches(json);
                foreach (Match m in ms)
                    cpFiles.Add(m.Value.TrimEnd('\"').Replace("/", "\\"));
                cpFiles.Add("asset/smoothscroll.min.js");
                cpFiles.Add("asset/vanilla-back-to-top.min.js");
                cpFiles.Add("asset/gumshoe.polyfills.min.js");
                cpFiles.Add("asset/main.js");

                foreach (var f in cpFiles)
                    File.Copy(srcdir + "\\" + f, dir + "\\" + f);

                System.Diagnostics.Process.Start("explorer.exe", dir);
            }
        }

    }
}
